#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import mrget
import pycdlib
from .._util import Util
from .._const import Arch, Version, Edition, Lang
from .._prototype import WindowsInstallationMediaBase
from .._errors import InstallMediaError


class LocalInstallationMedia(WindowsInstallationMediaBase):

    def __init__(self, iso_filepath, verify=True):
        super().__init__()

        self._isoPath = iso_filepath

        iso = pycdlib.PyCdlib()
        iso.open(self._isoPath)
        try:
            if len(iso.pvds) != 1:
                raise InstallMediaError("invalid ISO file, multiple PVDs")
            if iso.has_rock_ridge():
                raise InstallMediaError("invalid ISO file, Microsoft does not use Rock Ridge extension")

            label = Util.pycdlibGetLabel(iso)
            if label == "CCCOMA_X64FRE_EN-US_DV9":
                self._arch = Arch.X86_64
                self._version = Version.WINDOWS_10
                self._editions = [Edition.WINDOWS_10_HOME, Edition.WINDOWS_10_PRO, Edition.WINDOWS_10_EDUCATION, Edition.WINDOWS_10_ENTERPRISE, Edition.WINDOWS_10_ENTERPRISE_LTSB]
                self._languages = [Lang.en_US]
            else:
                raise InstallMediaError("invalid ISO file")
        finally:
            iso.close()

    def get_iso_filepath(self):
        return self._isoPath


class CloudInstallationMedia(WindowsInstallationMediaBase):

    def __init__(self, arch, version, edition, lang, local_iso_filepath=None, local_virtio_win_iso_filepath=None):
        assert version == Version.WINDOWS_10

        super().__init__()

        self._arch = arch
        self._version = version
        self._editions = [edition]
        self._languages = [lang]

        self._isoUrl = self._getIsoUrl()
        self._virtioWinIsoUrl = self._getVirtioWinIsoUrl()

        self._isoPath = local_iso_filepath
        self._virtioWinIsoPath = local_virtio_win_iso_filepath

        self._isoDownloaded = False
        if self._isoPath is not None and os.path.exists(self._isoPath):
            self._isoDownloaded = True

        self._virtioWinIsoDownloaded = False
        if self._virtioWinIsoPath is not None and os.path.exists(self._virtioWinIsoPath):
            self._virtioWinIsoDownloaded = True

    def get_iso_url(self):
        return self._isoUrl

    def download(self):
        if not self._isoDownloaded:
            assert self._isoPath is not None
            if self._isoUrl.startswith("mirror://"):
                url = mrget.target_urls(self._isoUrl, filter_key=lambda x: x["protocol"] in ["http", "https", "ftp"])[0]
            else:
                url = self._isoUrl
            Util.wgetDownload(url, self._isoPath)
            self._isoDownloaded = True

        if self._virtioWinIsoPath is not None and not self._virtioWinIsoDownloaded:
            if self._virtioWinIsoUrl.startswith("mirror://"):
                url = mrget.target_urls(self._virtioWinIsoUrl, filter_key=lambda x: x["protocol"] in ["http", "https", "ftp"])[0]
            else:
                url = self._virtioWinIsoUrl
            Util.wgetDownload(url, self._virtioWinIsoPath)
            self._virtioWinIsoDownloaded = True

    def get_iso_filepath(self):
        assert self._isoPath is not None
        assert self._isoDownloaded

        return self._isoPath

    def get_virtio_win_iso_filepath(self):
        assert self._virtioWinIsoPath is not None
        assert self._virtioWinIsoDownloaded

        return self._virtioWinIsoPath

    def _getIsoUrl(self):
        if self._arch == Arch.X86:
            assert False
        elif self._arch == Arch.X86_64:
            return "mirror://oldwin/Win10_22H2_English_x64v1.iso"
        else:
            assert False

    def _getVirtioWinIsoUrl(self):
        return "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/virtio-win-0.1.262-1/virtio-win-0.1.262.iso"


#    "win10x64": ("ce8005a659e8df7fe9b080352cb1c313c3e9adce", "https://hatching.dev/hatchvm/Win10_1703_English_x64.iso")
